package de.tum.in.eist.poll.client;


import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

import de.tum.in.eist.poll.pub.service.ExtPollService;
import de.tum.in.eist.poll.pub.service.ExtPollServiceAsync;
import de.tum.in.eist.poll.pub.service.PushService;
import de.tum.in.eist.poll.pub.service.PushServiceAsync;
import de.tum.in.eist.poll.pub.shared.LecturePush;
import de.tum.in.eist.poll.pub.shared.User;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class EIST_POLL implements EntryPoint {

	/**
	 * This is the entry point method.
	 */

	public static ExtPollServiceAsync service = GWT.create(ExtPollService.class);
	public static PushServiceAsync notificationService = GWT.create(PushService.class);
	public static User currentUser = null;
	public static int lastNotificationId = 0;
	
	/**
	 * Generates the RootPanel. Adds the login-panel.
	 */	
	public void onModuleLoad() {
		RootPanel root = RootPanel.get("login");
		root.add(new LoginView());
	}
	
	/**
	 * If there are statistic-updates avaible the user gets notified via a DialogBox.
	 */	
	public static void getNotifications(){
		AsyncCallback<LecturePush> callback = new AsyncCallback<LecturePush>() {
			
			@Override
			public void onSuccess(LecturePush result) {
				lastNotificationId = result.getId();
				final DialogBox notification = new DialogBox();
				notification.setText("Notification");
				VerticalPanel notificationContent = new VerticalPanel();
				notificationContent.add(new Label("The Statistic of Lecture\n"+result.getLecture().getName()+"\nhas been updated!"));
				Button ok = new Button();
				ok.setText("OK");
				ok.addClickHandler(new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						notification.hide();						
					}
				});
				notificationContent.add(ok);
				notification.add(notificationContent);
				notification.center();
				notificationService.getNotification(currentUser, lastNotificationId, this);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				notificationService.getNotification(currentUser, lastNotificationId, this);
			}
		};
		notificationService.getNotification(currentUser, lastNotificationId, callback);
	}
}
